package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
	dc "study/dcdatabase"
)

func main() {
	res := dc.GetCodemain()
	var ress []string
	for _, v := range res {
		mainde(v.Encode_code_str, v.Secert_key, v.Unique_id, ress)
	}
	fmt.Println("ress ", ress)
}

func mainde(ciphertextHex, keyHex, uniqueid string, ress []string) {
	//ciphertextHex := "29F933C178BB95B42D66299A9F5CC8D0" // 16字节的16进制密文
	//keyHex := "000102030405060708090a0b0c0d0e0f"        // 16字节的16进制密钥
	fmt.Println(ciphertextHex, keyHex, uniqueid)

	ciphertext, _ := hex.DecodeString(ciphertextHex)
	fmt.Println(ciphertext)
	key, _ := hex.DecodeString(keyHex)

	plaintext, err := decryptAESECB(ciphertext, key)
	if err != nil {
		fmt.Println("Error decrypting:", err)
		return
	}

	plaintextHex := hex.EncodeToString(plaintext)
	fmt.Println("Plaintext (in hex):", plaintextHex)
	// 将解密出的明文转换为字符串
	//fmt.Println("Plaintext (in string):", string(plaintext))

	// 截取字符串的后2位
	if len(plaintext) > 2 {
		//fmt.Println("Plaintext (in string):", string(plaintext[:len(plaintext)-2]))
		fmt.Println("Plaintext (in string):", string(plaintext[:len(plaintext)-2]), uniqueid)
		if string(plaintext[:len(plaintext)-2]) != uniqueid {
			ress = append(ress, string(plaintext[:len(plaintext)-2]))
		}
	}
}

func decryptAESECB(ciphertext []byte, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	plaintext := make([]byte, len(ciphertext))
	decrypter := NewECBDecrypter(block)
	decrypter.CryptBlocks(plaintext, ciphertext)

	return plaintext, nil
}

type ecbDecrypter struct {
	block cipher.Block
}

func NewECBDecrypter(block cipher.Block) cipher.BlockMode {
	return &ecbDecrypter{block}
}

func (x *ecbDecrypter) BlockSize() int { return x.block.BlockSize() }

func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
	if len(src)%x.block.BlockSize() != 0 {
		panic("crypto/cipher: input not full blocks")
	}
	if len(dst) < len(src) {
		panic("crypto/cipher: output smaller than input")
	}
	for len(src) > 0 {
		x.block.Decrypt(dst, src[:x.block.BlockSize()])
		src = src[x.block.BlockSize():]
		dst = dst[x.block.BlockSize():]
	}
}
